package com.example.mystoryapp2.ui.utils

import android.content.Context
import android.content.DialogInterface
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import com.example.mystoryapp2.R

/**
 * 这里Dialog和Toast弄混了 写到一块去了，后面如果有其他增加的内容就给他拆分开
 */
object DialogUtils {

    val dialogs: ArrayDeque<AlertDialog> = ArrayDeque()

    fun showLongMessage(context: Context, message: String) {
        Toast.makeText(context, message, Toast.LENGTH_LONG).show()
    }

    fun showLongMessage(context: Context, message: Int) {
        Toast.makeText(context, message, Toast.LENGTH_LONG).show()
    }

    fun showTwoBtn(
        context: Context,
        message: String,
        title: String,
        callBack: ICallBack,
        positiveTitle: String? = null,
        negativeTitle: String? = null
    ) {
        val dialog = AlertDialog.Builder(context)
            .setMessage(message)
            .setTitle(title)
            .setPositiveButton(
                positiveTitle ?: context.getString(R.string.btn_confirm)
            ) { dialog, _ -> callBack.onPositive(dialog) }
            .setNegativeButton(
                negativeTitle ?: context.getString(R.string.btn_cancel)
            ) { dialog, _ -> callBack.onNegative(dialog) }.create()
        showDialog(dialog)
    }

    fun showConfirmDialog(context: Context, f: () -> Unit) {
        showConfirmDialog(context, context.getString(R.string.message_confirm_cancel), f)
    }

    fun showConfirmDialog(context: Context, message: String, f: () -> Unit) {
        showTwoBtn(context,
            message,
            context.getString(R.string.title_tip), object : ICallBack {
                override fun onPositive(dialog: DialogInterface) {
                    f()
                }
            })
    }

    fun showDialog(dialog: AlertDialog) {
        dialog.setOnDismissListener {
            showDialog()
        }
        dialogs.add(dialog)
        showDialog()
    }

    private fun showDialog() {
        if (!dialogs.isEmpty()) {
            dialogs.removeFirst().show()
        }
    }

    interface ICallBack {
        fun onPositive(dialog: DialogInterface)
        fun onNegative(dialog: DialogInterface) {
            //nothing to do
        }
    }
}